package edu.um.token;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import edu.um.token.exception.InvalidTokenException;

public class Tokenizer {
  InputStreamReader reader;
  int column = 1;
  int line = 1;

  public Tokenizer(InputStream stream) {
    this.reader = new InputStreamReader(stream);
  }

  public boolean hasMoreToken() throws IOException {
    return reader.ready();

  }

  public Token nextToken() throws IOException, InvalidTokenException {
    int tokenColumn = column;
    int tokenLine = line;
    int chr = reader.read();
    updatePosition(chr);
    StringBuilder builder = new StringBuilder();
    boolean insideSegment = false;
    if (chr == '\'') {
      insideSegment = true;
    }
    while (chr != -1 && (!isTokenSeparator(chr) || insideSegment)) {
      if (chr != '\r') {
        builder.append((char) chr);
      }
      chr = reader.read();
      if (chr == '\'') {
        insideSegment = false;
      }
      updatePosition(chr);
    }
    return new Token(builder.toString(), tokenColumn, tokenLine);
  }

  private void updatePosition(int chr) {
    if (chr == '\n') {
      line++;
      column = 1;
    } else {
      column++;
    }

  }

  private boolean isTokenSeparator(int chr) {
    return (chr == ' ' || chr == '\n');
  }
}
